<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="个人信息填写" />
    <!-- /导航栏 -->

    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-cell-group inset>

        <van-field name='userImg' label="证件照" colon >
          <template #input>
             <van-image style="width:206px;height:244px;" :src="user.staffImg ? user.staffImg:require('@/assets/icon/tx.png')"/>
          </template>
        </van-field>
       <van-row gutter="20" style="margin-top:2px">
          <van-col span="10">
          </van-col>
          <van-col span="10">
              <van-uploader :after-read="afterRead" :max-count="1" accept="image/png, image/jpeg">
                <van-button icon="add-o">上传证件照</van-button>
              </van-uploader>
          </van-col>

        </van-row>

        <van-field
          v-model="user.name"
          name="userName"
          colon
          label="姓名"
          readonly
          placeholder="姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="user.idCode"
          name="idCode"
          label="身份证号"
          readonly
          placeholder="身份证号"
          :rules="[{ required: true, message: '请填写身份证号' }]"
        />

       <van-field
          v-model="user.sexLabel"
          is-link
          readonly
          name="userSex"
          label="性别"
          placeholder="点击选择性别"
          @click="sexShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="sexShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="sexList"
            show-toolbar
            :default-index="sexShowPickerDefaultIndex"
            @confirm="onSexConfirm"
            @cancel="sexShowPicker = false"
          />
        </van-popup>

        <van-field
          :value="user.teachAge"
          name="userTechYear"
          label="教龄"
          placeholder="教龄"
          readonly
          clickable
          @touchstart.native.stop="userTechYearShow = true"
        />
        <van-number-keyboard
          v-model="user.teachAge"
          :show="userTechYearShow"
          :maxlength="2"
          @blur="userTechYearShow = false"
        />
        <!--<van-field
          v-model="user.postLabel"
          is-link
          name="userPost"
          label="职务"
          placeholder="点击选择职务"
          @click="postShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="postShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="postList"
            :default-index="postShowPickerDefaultIndex"
            show-toolbar
            @confirm="onPostConfirm"
            @cancel="postShowPicker = false"
          />
        </van-popup>-->
        <van-field
          v-model="user.post"
          name="userPost"
          label="职务"
          placeholder="职务"
          :rules="[{ required: true, message: '请填写职务' }]"
        />
         <van-field
          v-model="user.technicalTitleLabel"
          is-link
          name="userTechnicalTitle"
          label="职称"
          placeholder="点击选择职称"
          @click="technicalTitleShowPicker = true"
          :rules="[{ required: true, message: '请填写职称' }]"
          arrow-direction="down" center
        />
        <van-popup v-model:show="technicalTitleShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="technicalTitleList"
            :default-index="technicalTitleShowPickerDefaultIndex"
            show-toolbar
            @confirm="onTechnicalTitleConfirm"
            @cancel="technicalTitleShowPicker = false"
          />
        </van-popup>

      </van-cell-group>

      <van-row gutter="20" style="margin-top:16px">
      <van-col span="3">
       </van-col>
        <van-col span="8">
          <van-button  block type="danger" @click="preStep">
            上一步
          </van-button>
        </van-col>
        <van-col span="2">
       </van-col>
        <van-col span="8">
          <van-button  block type="primary" native-type="submit">
            下一步
          </van-button>
                <van-col span="3">
       </van-col>
        </van-col>

      </van-row>



    </van-form>
    <!-- /登录表单 -->
  </div>
</template>
<script>
import { getCodeImg } from "@/api/login";
import { querySignature,uploadOSSFile,getSignature } from "@/api/oss";
import { getDicts,updGrExaminer } from "@/api/grantexaminer/grantexaminer";
import uuidv1 from "uuid/v1"
import { decrypt,encrypt,ossType } from '@/api/aesUtil'

export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      sexShowPicker:false,
      nationShowPicker:false,
      politicalShowPicker:false,
      technicalTitleShowPicker:false,
      userPostShowPicker:false,
      postShowPicker:false,
      userTechYearShow:false,
      sexShowPickerDefaultIndex:0,
      technicalTitleShowPickerDefaultIndex:0,
      postShowPickerDefaultIndex:0,
      loginInfo:{},
      user: {
        staffImg:null,
        name: '',
        idCode: '',
        sex: '',
        sexLabel: '',
        nation: '',
        nationLabel: '',
        political: '',
        politicalLabel: '',
        teachAge: "0",
        post: '',
        postLabel: '',
        technicalTitle: '',
        technicalTitleLabel: '',
      },
      sexList:[],
      nationList:[],
      politicalList:[],
      technicalTitleList:[],
      userPostList:[],
      postList:[],
      userFormRules: {
        mobile: [{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8|9]\d{9}$/,
          message: '手机号格式错误'
        }],
        code: [{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }]
      },
      clent: null
    }
  },
  computed: {},
  watch: {},
  created () {
    if(localStorage.getItem('userInfo')==''||localStorage.getItem('userInfo')==null)
    {
      this._routeReplace('loginPage');
      return;
    }
    else
    {
      this.loginInfo = JSON.parse(localStorage.getItem('userInfo'));
      console.log( this.loginInfo);
      this.user.name = this.loginInfo.name
      this.user.idCode = this.loginInfo.idcard
      this.user.staffImg = this.loginInfo.photoUrl
      this.user.teachAge = this.loginInfo.teachAge==null?'0':''+this.loginInfo.teachAge
      this.user.post = this.loginInfo.post

      getDicts('sys_user_sex').then(res=>{
        if(res.code===200){
          this.sexList = res.data
        }
        else{
          this.sexList = []
        }
        this.sexList.forEach((item,index)=>
        {
          if(item.dictValue==this.loginInfo.sex){
            this.user.sex = this.loginInfo.sex
            this.user.sexLabel = item.dictLabel
            this.sexShowPickerDefaultIndex = index
            return
          }
        })

      })
      getDicts('technical_title').then(res=>{
        if(res.code===200){
          this.technicalTitleList = res.data
        }
        else{
          this.technicalTitleList = []
        }
        this.technicalTitleList.forEach((item,index)=>
        {
          if(item.dictValue==this.loginInfo.technicalTitle){
            this.user.technicalTitle = this.loginInfo.technicalTitle
            this.user.technicalTitleLabel = item.dictLabel
            this.technicalTitleShowPickerDefaultIndex = index
            return
          }
        })
      })
      /*getDicts('sys_post').then(res=>{
        if(res.code===200){
          this.postList = res.data
        }
        else{
          this.postList = []
        }
        this.postList.forEach((item,index)=>
        {
          if(item.dictValue==this.loginInfo.post){
            this.user.post = this.loginInfo.post
            this.user.postLabel = item.dictLabel
            this.postShowPickerDefaultIndex = index
            return
          }
        })
      })*/

    }
  },
  mounted () {
    this.initOss();
  },
  methods: {
    preStep()
    {
      localStorage.setItem('backflag','1');
      this._routeReplace('loginPage');
    },
    onSexConfirm(val) {
      this.sexShowPicker = false
      this.user.sex = val.dictValue
      this.user.sexLabel = val.dictLabel
    },
    onNationConfirm(val) {
      this.nationShowPicker = false
      this.user.nation = val.dictValue
      this.user.nationLabel = val.dictLabel
    },
    onPoliticalConfirm(val) {
      this.politicalShowPicker = false
      this.user.political = val.dictValue
      this.user.politicalLabel = val.dictLabel
    },
    onTechnicalTitleConfirm(val) {
      this.technicalTitleShowPicker = false
      this.user.technicalTitle = val.dictValue
      this.user.technicalTitleLabel = val.dictLabel
    },

    onPostConfirm(val) {
      this.postShowPicker = false
      this.user.post = val.dictValue
      this.user.postLabel = val.dictLabel
    },
    initOss () {
      let that = this
      querySignature("init").then(res=>{
        if (res.code === 0 && res.data.tyCloudFlag=='1') {
          that.client = new ObsClient({
              access_key_id: res.data.accessid,
              secret_access_key:  decrypt(res.data.signature),
              server : res.data.endPoint
          });
        }
      })
    },
    async afterRead(info) {
      const { file } = info
      let that = this
      try {
        const signRes = await querySignature("image")
        if (signRes.code === 0) {
            if(signRes.data.tyCloudFlag=='0'){
              const filename = file.name;
              const size = file.size;
              console.log("signRes",signRes,filename)
              const fileExt = filename.split(".");
              const uuid = uuidv1();
              let formData = new FormData();
              //注意formData里append添加的键的大小写
              formData.append('key', signRes.data.dir + uuid + "." + fileExt[1]); //存储在oss的文件路径
              formData.append('OSSAccessKeyId', signRes.data.accessid); //accessKeyId
              formData.append('policy', signRes.data.policy); //policy
              formData.append('Signature', signRes.data.signature); //签名
              //formData.append('callback', signRes.callback); //回调
              formData.append('success_action_status', 200); //成功后返回的操作码
              //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
              formData.append("file", file);

              var res = await uploadOSSFile(signRes.data.host, formData);
              const imageUrl = signRes.data.host.replaceAll('http://','https://')+'/'+signRes.data.dir + uuid + "." + fileExt[1];


              this.user.staffImg = imageUrl


              this.$toast.success('上传成功')
            }else{

              const filename = file.name;
              const size = file.size;

              const fileExt = filename.split(".");
              const uuid = uuidv1();

              var params = {
                Body: file,
                Bucket: signRes.data.bucket,
                Key: signRes.data.dir + uuid + "." + fileExt[1]
              }
              that.client.putObject(params, function (err, data) {
                if (err) {
                  that.$toast.success('上传失败')
                } else {

                  const imageUrl = signRes.data.host+'/'+signRes.data.dir + uuid + "." + fileExt[1];

                  that.user.staffImg = imageUrl

                  that.$toast.success('上传成功')
                }
              })
            }
        }
      }catch (e) {
        console.log(e);
        this.$toast.fail('上传失败')
      }
    },
    oversize(e) {
      this.$toast.fail("图片过大！");
    },
    async onSubmit () {
      console.log(this.user.staffImg);
      if(this.user.staffImg==null || this.user.staffImg==''){
        this.$toast.fail('请先上传照片');
        return;
      }
      // 3. 提交表单请求登录
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })
      try {

        this.loginInfo.name = this.user.name
        this.loginInfo.idcard = this.user.idCode
        this.loginInfo.photoUrl = this.user.staffImg
        this.loginInfo.teachAge = parseInt(this.user.teachAge)
        this.loginInfo.post = this.user.post
        this.loginInfo.sex = this.user.sex
        this.loginInfo.technicalTitle = this.user.technicalTitle

        const res = await updGrExaminer(this.loginInfo)
        if(res.code===200){
          localStorage.setItem('userInfo', JSON.stringify(this.loginInfo));
          this.$toast.success('保存成功')
          this._routeReplace('enrollImg');
        }else{
          this.$toast.fail(res.msg)
        }


      } catch (err) {

        this.$toast.fail('保存失败，'+err.msg)

      }
    }
  }
}
</script>
<style scoped lang="less">

.login-container {
  .toutiao {
    font-size: 37px;
  }
  .send-sms-btn {
    width: 152px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
}
</style>
